package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.UserCouponMapper;
import com.neusoft.elmboot.po.UserCoupon;
import com.neusoft.elmboot.service.UserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Service
public class UserCouponServiceImpl implements UserCouponService {
	
	@Autowired
	private UserCouponMapper userCouponMapper;
	
	private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	
	@Override
	@Transactional
	public UserCoupon createCoupon(String userId, Integer itemId, String couponName, Double discountAmount, Double minimumAmount, int validDays) {
		// 生成唯一的优惠券编码
		String couponCode = generateCouponCode();
		
		// 计算过期时间
		LocalDateTime expiryDateTime = LocalDateTime.now().plusDays(validDays);
		String expiryDate = expiryDateTime.format(dateTimeFormatter);
		
		UserCoupon coupon = UserCoupon.builder()
			.userId(userId)
			.itemId(itemId)
			.couponCode(couponCode)
			.couponName(couponName)
			.discountAmount(discountAmount)
			.minimumAmount(minimumAmount != null ? minimumAmount : 0.0)
			.expiryDate(expiryDate)
			.status(1) // 1: 未使用
			.build();
		
		userCouponMapper.insertCoupon(coupon);
		return coupon;
	}
	
	@Override
	public List<UserCoupon> getAvailableCoupons(String userId) {
		// 先更新过期的优惠券状态
		userCouponMapper.updateExpiredCoupons();
		return userCouponMapper.getAvailableCouponsByUserId(userId);
	}
	
	@Override
	public List<UserCoupon> getUserCoupons(String userId) {
		return userCouponMapper.getCouponsByUserId(userId);
	}
	
	@Override
	public UserCoupon getCouponById(Integer couponId) {
		return userCouponMapper.getCouponById(couponId);
	}
	
	@Override
	@Transactional
	public boolean useCoupon(Integer couponId, Integer orderId) {
		UserCoupon coupon = userCouponMapper.getCouponById(couponId);
		
		if (coupon == null) {
			return false;
		}
		
		// 检查优惠券状态
		if (coupon.getStatus() != 1) {
			return false; // 优惠券已使用或已过期
		}
		
		// 检查过期时间
		LocalDateTime expiryDateTime = LocalDateTime.parse(coupon.getExpiryDate(), dateTimeFormatter);
		if (LocalDateTime.now().isAfter(expiryDateTime)) {
			userCouponMapper.updateCouponStatus(couponId, 3); // 标记为已过期
			return false;
		}
		
		// 使用优惠券
		int result = userCouponMapper.useCoupon(couponId, orderId);
		return result > 0;
	}
	
	@Override
	public boolean validateCoupon(Integer couponId, Double orderAmount) {
		UserCoupon coupon = userCouponMapper.getCouponById(couponId);
		
		if (coupon == null || coupon.getStatus() != 1) {
			return false;
		}
		
		// 检查过期时间
		LocalDateTime expiryDateTime = LocalDateTime.parse(coupon.getExpiryDate(), dateTimeFormatter);
		if (LocalDateTime.now().isAfter(expiryDateTime)) {
			return false;
		}
		
		// 检查最低消费金额
		if (orderAmount < coupon.getMinimumAmount()) {
			return false;
		}
		
		return true;
	}
	
	@Override
	@Transactional
	public void updateExpiredCoupons() {
		userCouponMapper.updateExpiredCoupons();
	}
	
	/**
	 * 生成唯一的优惠券编码
	 */
	private String generateCouponCode() {
		return "COUPON_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
	}
}
